const app = getApp();
const util = require('../../../utils/util.js');
const lbbService = require('../../../pages/service/service.js');
const lbbTaskService = require('../service/task-service.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        taskDataList: [{}],
        showProject: false,
        showType:false,
        showtaskClass: false,
        showPlace: false,
        showUser: false,
        showRuleTime: false,
        columnsProject: [],
        columnsType:[{ text: '机构', value:0  },{ text: '代理', value:1 }],
        mainActiveIndex: 0,
        seletList: [],
        institutionList: [],
        userList: [],
        minDate: new Date().getTime(),
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`;
            }
            if (type === 'month') {
                return `${value}月`;
            }
            return value;
        },
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        console.log(22, options)
        that.setData({
            userId: options.userId
        })
        if(options.hosId) {
            that.setData({
                hosId:options.hosId,
                hosName:options.hosName,
                taskDataList:[
                    {
                        placeTypeText:'机构',
                        placeType:0,
                        placeName:options.hosName,
                        placeId:options.hosId
                    }
                ]
            })
        }
        that.getProjectList()
        that.getInstructorList()
        if(options.taskId){
            lbbTaskService.getMarketTaskDevOpsById({taskId:options.taskId},function(res) {
                if(res.data.taskImages){
                    res.data.taskImages=res.data.taskImages.split(',')  
                }
                wx.setNavigationBarTitle({
                    title:'编辑任务'
                })
                that.data.taskDataList=[res.data]
                that.setData({
                    taskDataList:that.data.taskDataList,
                    taskId:options.taskId
                })
            })
        }
    },
    //获取项目列表
    getProjectList() {
        let that = this
        lbbTaskService.getDictByCode({
            code: 'taskProject'
        }, function (res) {
            that.setData({
                columnsProject: res.data
            })
        })
    },
    //获取任务分类列表
    getTaskCategory(code) {
        let that = this
        lbbTaskService.getAllCategoryAndSubList({code}, function (res) {
            that.setData({
                seletListAll: JSON.parse(JSON.stringify(res.data)),
                seletList: res.data,
            })
        })
    },
    //获取机构列表
    getMechanismList(keywords) {
        let that = this
        lbbTaskService.getAllMechanismList({
            pageNo: 1,
            pageSize: 100,
            keywords: keywords
        }, function (res) {
            that.setData({
                institutionList: res.data.records,
            })
        })
    },
    //代理商列表
    getAllAgent(keywords){
        let that=this
        lbbTaskService.getAllAgent({
            pageNo: 1,
            pageSize: 100,
            keywords:keywords
        }, function (res) {
            that.setData({
                institutionList: res.data.records,
            })
        })
    },
    //获取指令人
    getInstructorList() {
        let that = this
        lbbTaskService.getAllUserList({}, function (res) {
            that.setData({
                userListAll: JSON.parse(JSON.stringify(res.data)),
                userList: res.data,
            })
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },
    //打开任务项目弹框
    onBindProject(e) {
        this.setData({
            showProject: true,
            taskIndex: e.currentTarget.dataset.index
        })
    },
    //确认选择项目
    okject(e) {
        this.data.taskDataList[this.data.taskIndex].taskProjectText = e.detail.value.text
        this.data.taskDataList[this.data.taskIndex].taskProject = e.detail.value.value
        this.setData({
            taskDataList: this.data.taskDataList,
            showProject: false
        })
        this.changeClassify(e.detail.value.value,this.data.taskDataList[this.data.taskIndex].placeType)
    },
    //关闭遮罩层
    onCloseProject() {
        this.setData({
            showProject: false
        })
    },
    //取消选择
    cancelject() {
        this.setData({
            showProject: false
        })
    },
    //打开任务类型弹窗
    onBindPlaceType(e){
        this.setData({
            showType: true,
            taskIndex: e.currentTarget.dataset.index
        })
    },
    //确认类型
    okType(e){
        this.data.taskDataList[this.data.taskIndex].placeTypeText = e.detail.value.text
        this.data.taskDataList[this.data.taskIndex].placeType = e.detail.value.value
        this.data.taskDataList[this.data.taskIndex].placeName = ''
        this.data.taskDataList[this.data.taskIndex].placeId = ''
        this.setData({
            taskDataList: this.data.taskDataList,
            showType: false
        })
       this.changeClassify(this.data.taskDataList[this.data.taskIndex].taskProject,e.detail.value.value)
       if(e.detail.value.value==0){
        this.getMechanismList('')
       }else if(e.detail.value.value==1){
        this.getAllAgent('')
       }
    },
     //关闭遮罩层
     onCloseType() {
        this.setData({
            showType: false
        })
    },
    //取消选择
    cancelType() {
        this.setData({
            showType: false
        })
    },
    //打开任务分类弹框
    onBindtaskClass(e) {
        this.setData({
            showtaskClass: true,
            taskIndex: e.currentTarget.dataset.index
        })
    },
    //关闭弹出层
    onClosetaskClass() {
        this.setData({
            showtaskClass: false
        })
    },
    //分类树侧边栏
    onClickNav({
        detail = {}
    }) {
        this.setData({
            mainActiveIndex: detail.index || 0,
        })
    },
    //关键任务分类字搜索
    changeSelect(e) {
        let that = this
        if (e.detail) {
            let listItemList = that.data.seletListAll[that.data.mainActiveIndex].children.filter(item => item.text.indexOf(e.detail) != -1)
            that.data.seletList[that.data.mainActiveIndex].children = JSON.parse(JSON.stringify(listItemList))
            that.setData({
                seletList: that.data.seletList
            })
        } else {
            that.setData({
                seletList: JSON.parse(JSON.stringify(that.data.seletListAll))
            })
        }
    },
    //点击确定分类
    onClickItem({
        detail = {}
    }) {
        this.data.taskDataList[this.data.taskIndex].taskClassificationNameTwo = detail.text
        this.data.taskDataList[this.data.taskIndex].taskClassificationId = detail.id
        this.setData({
            taskDataList: this.data.taskDataList,
            showtaskClass: false
        })
    },
    //点击打开机构弹出层
    onBindplace(e) {
        this.setData({
            showPlace: true,
            taskIndex: e.currentTarget.dataset.index
        })
    },
    //关闭弹框
    onClosePlace() {
        this.setData({
            showPlace: false,
        })
    },
    //搜索机构的关键字
    changePlacez(e) {
        console.log(e)
        this.setData({
            InstitutionalKeywords: e.detail ? e.detail : ''
        })
    },
    //关键字搜索机构
    onClickSearch() {
        if(this.data.taskDataList[this.data.taskIndex].placeType==0){
            this.getMechanismList(this.data.InstitutionalKeywords?this.data.InstitutionalKeywords:'')
        }else{
            this.getAllAgent(this.data.InstitutionalKeywords?this.data.InstitutionalKeywords:'')
        }  
    },
    //点击选择机构
    btnPlace(e) {
        console.log(e)
        this.data.taskDataList[this.data.taskIndex].placeName = e.currentTarget.dataset.name
        this.data.taskDataList[this.data.taskIndex].placeId = e.currentTarget.dataset.id
        this.setData({
            taskDataList: this.data.taskDataList,
            showPlace: false
        })
    },
    //添加医院的页面
    btnAddHospital(){
        wx.navigateTo({
            url: `/pkgTask/pages/addHospital/index`
        })
    },
    //添加代理的页面
    btnAddAgent(){
        wx.navigateTo({
            url: `/pkgTask/pages/addAgent/index`
        })
    },
    //打开指令弹出层
    onBindUser(e) {
        this.setData({
            showUser: true,
            taskIndex: e.currentTarget.dataset.index
        })
    },
    //关闭指令人弹框
    onCloseUser() {
        this.setData({
            showUser: false,
        })
    },
    //搜索指令人
    changeUser(e) {
        let that = this
        if (e.detail) {
            let listItemList = that.data.userListAll.filter(item => item.label.indexOf(e.detail) != -1)
            that.data.userList = JSON.parse(JSON.stringify(listItemList))
            that.setData({
                userList: that.data.userList
            })
        } else {
            that.setData({
                userList: JSON.parse(JSON.stringify(that.data.userListAll))
            })
        }
    },
    //选择指令人
    btnUser(e) {
        this.data.taskDataList[this.data.taskIndex].instructorName = e.currentTarget.dataset.name
        this.data.taskDataList[this.data.taskIndex].instructor = e.currentTarget.dataset.id
        this.setData({
            taskDataList: this.data.taskDataList,
            showUser: false
        })
    },
    //打开截至时间选择弹出层
    onBindRuleTime(e) {
        this.setData({
            showRuleTime: true,
            taskIndex: e.currentTarget.dataset.index
        })
    },
    //关闭时间弹出层
    onCloseRuleTime() {
        this.setData({
            showRuleTime: false,
        })
    },
    //确定选择日期
    okDate(e) {
        let reg = /\//g;
        let date = util.formatTime(new Date(e.detail)).substr(0, 10).replace(reg, '-')
        this.data.taskDataList[this.data.taskIndex].handleRuleTime = date
        this.setData({
            taskDataList: this.data.taskDataList,
            showRuleTime: false,
        })
    },
    //取消选择日期
    cancelDate() {
        this.setData({
            showRuleTime: false,
        })
    },
    //备注内容
    changeRemark(e) {
        this.data.taskDataList[e.currentTarget.dataset.index].taskDesc = e.detail.value
        this.setData({
            taskDataList: this.data.taskDataList
        })
    },
    //上传图片回调
    setImgArr(e) {
        let that=this
        let imgArray = e.detail;
        let newUpLoadImg = []
        let oldUpLoadImg = []
        console.log('图片',imgArray)
        imgArray.forEach(item => {
            if (item.indexOf('http://tmp/') != -1||item.indexOf('wxfile://tmp')!=-1) {
                newUpLoadImg.push(item)
            } else {
                oldUpLoadImg.push(item)
            }
        })
        wx.showLoading({
            title: '正在上传图片',
            mask: true
        })
        util.newUpLoadImg(app.globalData.header, newUpLoadImg, 0, [], function (imgIdArray) {
            console.log('item================>', imgIdArray)
            wx.hideLoading()
            oldUpLoadImg.push(...imgIdArray)
        });
        that.data.taskDataList[e.currentTarget.dataset.index].taskImages = oldUpLoadImg
        // that.setData({
        //     taskDataList:that.data.taskDataList
        // })
    },
    //新增任务
    addTask() {
        if(this.data.hosId) {
            this.data.taskDataList.push({placeTypeText:'机构',placeType:0,placeName:this.data.hosName,placeId:this.data.hosId})
        } else {
            this.data.taskDataList.push({})
        }
        this.setData({
            taskDataList: this.data.taskDataList
        })
    },
    //删除任务
    delTask(e) {
        this.data.taskDataList.splice(e.currentTarget.dataset.index, 1)
        this.setData({
            taskDataList: this.data.taskDataList
        })
    },
    //提交任务
    btnSubmit() {
        let that = this
        that.data.taskDataList.forEach(item => {
            item.userId = that.data.userId
            if (!item.taskDesc) {
                item.taskDesc = ''
            }
            if(!item.taskImages){
                item.taskImages=''
            }else{
                item.taskImages=item.taskImages.toString()
            }
        })
        if(!that.data.taskId){
           lbbTaskService.addMarketTaskDevOps({taskList:JSON.stringify(that.data.taskDataList)},function(res) {
            wx.navigateBack({
                delta: 1
              })
        })  
        }else{
            lbbTaskService.editMarketTaskDevOps({...that.data.taskDataList[0]},function(res) {
                wx.navigateBack({
                    delta: 1
                  })
            }) 
        }
       
    },
    //任务分类的列表数据变化
    changeClassify(taskProject,placeType) {
        console.log(456,taskProject,placeType)
        this.data.taskDataList[this.data.taskIndex].taskClassificationNameTwo = ''
        this.data.taskDataList[this.data.taskIndex].taskClassificationId = ''
        this.setData({
            taskDataList:this.data.taskDataList
        })
        if(taskProject=='ejia'&&placeType==0){
            this.getTaskCategory('B22A01')
        }else if(taskProject=='ejia'&&placeType==1){
            this.getTaskCategory('B22A03')
        }else if(taskProject=='weilao'&&placeType==0){
            this.getTaskCategory('B22A04')
        }else if(taskProject=='weilao'&&placeType==1){
            this.getTaskCategory('B22A05')
        }
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        if(this.data.taskDataList[this.data.taskIndex]?.placeType==0){
            this.getMechanismList(this.data.InstitutionalKeywords?this.data.InstitutionalKeywords:'')
        }else{
            this.getAllAgent(this.data.InstitutionalKeywords?this.data.InstitutionalKeywords:'')
        } 
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})